<?php

namespace application\common\models;

/**
 * 关联链接
 */
class newskey extends base_model {

    public static function parse_related_link($content, $extent) {
        $allextent = array('article' => 0, 'forum' => 1, 'group' => 2, 'blog' => 3);
        $ret = db('newskey')->select();
        if ($ret && isset($allextent[$extent])) {
            $searcharray = $replacearray = array();
            foreach ($ret as $link) {
                $link['extent'] = sprintf('%04b', $link['extent']);
                if ($link['extent'][$allextent[$extent]] && $link['name'] && $link['url']) {
                    $searcharray[$link[name]] = '/(' . preg_quote($link['name']) . ')/i';
                    $replacearray[$link[name]] = "<a href=\"$link[url]\" target=\"_blank\" class=\"relatedlink\">$link[name]</a>";
                }
            }
            if ($searcharray && $replacearray) {
                $content = preg_replace("/(<script\s+.*?>.*?<\/script>)|(<a\s+.*?>.*?<\/a>)|(<img\s+.*?[\/]?>)|(\[attach\](\d+)\[\/attach\])/ies", "helper_seo::base64_transform('encode', '<relatedlink>', '\\1\\2\\3\\4', '</relatedlink>')", $content);
                $content = preg_replace($searcharray, $replacearray, $content, 1);
                $content = preg_replace("/<relatedlink>(.*?)<\/relatedlink>/ies", "helper_seo::base64_transform('decode', '', '\\1', '')", $content);
            }
        }
        return $content;
    }

}
